//
//  ZZCAgentController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCCompanyInfoController.h"
#import "ZZCScanController.h"
#import "ZZCCompanyInfoView.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface ZZCCompanyInfoController ()<UITextFieldDelegate,UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) ZZCCompanyInfoView *InfoView;
@property (strong, nonatomic) ZZCMenuView *menuViewA;
@property (strong, nonatomic) ZZCMenuView *menuViewB;
@property (strong, nonatomic) ZZCMenuView *menuViewC;
@property (copy, nonatomic) NSString *enterpriseName;

@property (copy,   nonatomic) NSString *imgUrl;
@property (retain, nonatomic) NSURL *uurl;

@property (assign, nonatomic) NSInteger rankIndex;
@property (nonatomic, assign) NSInteger photoType;//图片类型
@property (nonatomic,   copy) NSString *imageUrl_1;
@property (nonatomic,   copy) NSString *imageUrl_2;

@property (nonatomic, strong) CityChoose *cityChoose;    /** 城市选择 */
@property (copy, nonatomic) NSString *province;
@property (copy, nonatomic) NSString *city;
@property (copy, nonatomic) NSString *area;

@end

@implementation ZZCCompanyInfoController


- (void)viewDidLoad {
    [super viewDidLoad];
    //状态标签
    UIView *subviews  = [self.InfoView viewWithTag:1447];
    subviews.hidden = YES;

    self.title = @"完善企业信息";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.InfoView];
    [self.InfoView.rankBtn addTarget:self action:@selector(rankBtnClick) forControlEvents:UIControlEventTouchUpInside];

    [self.InfoView.regionBtn addTarget:self action:@selector(regionBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.InfoView.natureBtn addTarget:self action:@selector(natureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.InfoView.bgScrollView.delegate = self;
    
    __weak typeof (self) weakself = self;

    //企业性质
    NSArray *arr1 = @[@"国有",@"民企",@"个体",@"其他"];
    self.menuViewB = [[ZZCMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.InfoView.natureView.frame), ZZCScreenW, 132) contentArray:arr1];
    
    self.menuViewB.block = ^(BOOL isSeletct ,NSString *title){
        weakself.menuViewB.hidden = YES;
        if (title.length != 0) {
            [weakself.InfoView.natureBtn setTitle:title forState:UIControlStateNormal];
        }
    };
    
    self.menuViewB.hidden = YES;
    [self.InfoView addSubview:self.menuViewB];
    self.menuViewB.y = self.InfoView.natureView.y+44;
    
    [self bottomBtn];
    
    [_InfoView.licenseBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_InfoView.accreditBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.InfoView.regionBtn addTarget:self action:@selector(regionBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)btnClick:(UIButton *)sender {
    if (sender.tag == 996) {
        _photoType = 1;
    } else if (sender.tag == 997) {
        _photoType = 2;
    }
    [self userEvent];
}

//调用相机
- (void)userEvent {
    [self cameraBtnDidClick];
}

-(void)cameraBtnDidClick{
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor colorWithHex:0xEB6927];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:1];
    }];
    
    UIAlertAction * choice = [UIAlertAction actionWithTitle:@"相册选择" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:0];
    }];
    
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    
    [alertController addAction:photo];
    [alertController addAction:choice];
    [alertController addAction:cancel];
    [self showDetailViewController:alertController sender:nil];
    
}

#pragma mark - 相册 相机
- (void)openPhotoWithType:(int)type
{
    if ([self getMediaTypeVideo]) {  //获取相机权限
        UIImagePickerControllerSourceType sourceType = type;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else{
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        
        NSLog(@"相机受限");
    }
}

#pragma mark 判断摄像头权限
-(bool)getMediaTypeVideo
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    
    if(author == ALAuthorizationStatusRestricted){// 受限制 家长权限之类的
        
        return NO;
        
    } else if(author == ALAuthorizationStatusDenied){// 已经拒绝的
        
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        return NO;
    } else if(author == ALAuthorizationStatusAuthorized){// 已允许的
        
        return YES;
        
    } else if(author == ALAuthorizationStatusNotDetermined){// 还没决定的
        
        return YES;
    } else {
        
        return NO;
    }
}
#pragma mark - imagePicker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *img = [self scaleToSize:[info objectForKey:@"UIImagePickerControllerEditedImage"] size:CGSizeMake(300, 300)];
    ZZCLog(@"%@",img);
    [self uploadImage:img];
    
}
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


#pragma mark - 上传图片
- (void)uploadImage:(UIImage *)img {
    
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *param = @{@"token":token,@"type":@(2)};
    [[ZZCRequest sharedNetworkTools] uploadWithURL:ZZCURL_API_UPLOAD params:param formBoundary:img success:^(NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",data);
        self.imgUrl = data[@"data"][@"url"];
        _uurl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ZZCURL_API,_imgUrl]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updetaMeInfo" object:self];
        [self newnewIMG];
    } fail:^(NSError * _Nonnull error, NSString * _Nonnull msg, NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",error);
    }];
}
- (void)newnewIMG {
    if (_photoType == 1) {
        [self.InfoView.licenseImageV sd_setImageWithURL:_uurl placeholderImage:[UIImage imageNamed:@"1.jpeg"]];
        _imageUrl_1 = _imgUrl;
    } else if (_photoType == 2) {
        [self.InfoView.accreditImageV sd_setImageWithURL:_uurl placeholderImage:[UIImage imageNamed:@"1.jpeg"]];
        _imageUrl_2 = _imgUrl;
    }
}
#pragma mark - 提交申请
- (void)putIn {
    ZZCLog(@"提交申请");
    if (_InfoView.enterpriseNameTextField.text == nil
        ||_InfoView.natureBtn.titleLabel.text == nil
        ||_InfoView.enterpriseLegalTextField.text == nil
        ||_InfoView.enterprisePhoneTextField.text == nil
        ||_InfoView.legalMailboxTextField.text == nil
        ||_imageUrl_1 == nil
        ||_imageUrl_2 == nil
        ||_InfoView.enterpriseAddressTextField.text == nil) {
        [SVProgressHUD showInfoWithStatus:@"请填写申请信息"];
        return;
    }

    NSString *token = ZZCNSUserDefaults(@"token");
    NSDate *currentDate = [NSDate date];
    NSString *timeStr = [NSString stringWithFormat:@"%ld",(long)[currentDate timeIntervalSince1970]];
    NSDictionary *dict = @{
                           @"token":token,
                           @"company_name":_InfoView.enterpriseNameTextField.text,
                           @"type":_InfoView.natureBtn.titleLabel.text,
                           @"corporation":_InfoView.enterpriseLegalTextField.text,
                           @"phone":_InfoView.enterprisePhoneTextField.text,
                           @"email":_InfoView.legalMailboxTextField.text,
                           @"license":_imageUrl_1,
                           @"proxy":_imageUrl_2,
                           @"address":_InfoView.enterpriseAddressTextField.text
                           };
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{
                            @"timestamp":timeStr,@"sign":sign,
                            @"token":token,
                            @"company_name":_InfoView.enterpriseNameTextField.text,
                            @"type":_InfoView.natureBtn.titleLabel.text,
                            @"corporation":_InfoView.enterpriseLegalTextField.text,
                            @"phone":_InfoView.enterprisePhoneTextField.text,
                            @"email":_InfoView.legalMailboxTextField.text,
                            @"license":_imageUrl_1,
                            @"proxy":_imageUrl_2,
                            @"address":_InfoView.enterpriseAddressTextField.text

                            };
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_PROMESS parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"@@@@@@@@@@@&&&&&&&&&&&&%@",responseObject);
            if ([responseObject[@"code"] isEqual:@(200)]) {
                _InfoView.statusLabel.text = responseObject[@"msg"];
                //            _stateLabel.hidden = NO;
                UIView *subviews  = [self.InfoView viewWithTag:1447];
                subviews.hidden = NO;
                
                UIButton *button = [self.view viewWithTag:1124];
                button.hidden = YES;
                
            } else if([responseObject[@"code"] isEqual:@(400)]){
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
            
        } else {
            NSLog(@"%@",error);
            //            [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
        }
    }];
}

- (void)bottomBtn {
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, ZZCScreenH-113, ZZCScreenW, 49)];
    btn.backgroundColor = [UIColor colorWithHex:0xEA6E25];
    [btn setTitle:@"下一步" forState:0];
    [btn addTarget:self action:@selector(putIn) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.font = FONT(19);
    [btn setTag:1124];
    [self.view addSubview:btn];
}
- (void)nextClick {
    ZZCLog(@"重新申请");
    ZZCScanController *scan = [ZZCScanController new];
    [self.navigationController pushViewController:scan animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.menuViewA.y = self.InfoView.rankView.y+44 - scrollView.contentOffset.y;
    self.menuViewB.y = self.InfoView.natureView.y+44 - scrollView.contentOffset.y;
    self.menuViewC.y = self.InfoView.regionView.y+44 - scrollView.contentOffset.y;
}


- (void)rankBtnClick {
    [self.view endEditing:YES];
    self.menuViewA.hidden = !self.menuViewA.hidden;
    self.menuViewB.hidden = YES;
    self.menuViewC.hidden = YES;
    
}
- (void)natureBtnClick {
    [self.view endEditing:YES];
    self.menuViewB.hidden = !self.menuViewB.hidden;
    self.menuViewA.hidden = YES;
    self.menuViewC.hidden = YES;
    
}
- (void)regionBtnClick {
//    [self.view endEditing:YES];
//    self.menuViewC.hidden = !self.menuViewC.hidden;
//    self.menuViewA.hidden = YES;
//    self.menuViewB.hidden = YES;
    self.cityChoose = [[CityChoose alloc] init];
    __weak typeof(self) weakSelf = self;
    self.cityChoose.config = ^(NSString *province, NSString *city, NSString *town){
        weakSelf.InfoView.regionLabel.text = [NSString stringWithFormat:@"%@-%@-%@",province,city,town];
        weakSelf.province = province;
        weakSelf.city = city;
        weakSelf.area = town;
    };
    [self.view addSubview:self.cityChoose];

}
#pragma mark - 值接收
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.menuViewA.hidden = YES;
    self.menuViewB.hidden = YES;
    self.menuViewC.hidden = YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.InfoView.enterpriseNameTextField) {
        //企业名字值接收,自己创建属性接收需要的值
        self.enterpriseName = textField.text;
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.InfoView.enterpriseLegalTextField){
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.InfoView.enterprisePhoneTextField){
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.InfoView.legalMailboxTextField){
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.InfoView.enterpriseAddressTextField){
        ZZCLog(@"%@",textField.text);
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.InfoView.enterprisePhoneTextField) {
        //用来做长度限制；
        if (range.location>=11) {
            return NO;
        }
    }
    return YES;
    
}


- (ZZCCompanyInfoView *)InfoView {
    if (_InfoView == nil) {
        _InfoView = [ZZCCompanyInfoView InfoView];
        _InfoView.frame = CGRectMake(0, 0, ZZCScreenW, ZZCScreenH);
        _InfoView.enterpriseNameTextField.delegate = self;
        _InfoView.enterpriseLegalTextField.delegate = self;
        _InfoView.enterprisePhoneTextField.delegate = self;
        _InfoView.legalMailboxTextField.delegate = self;
    }
    return _InfoView;
}
@end
